/**
 * Filename: fig9-12_orphaned_process.c
 * Author:   csbonkers
 * Contact:  csbonkers@mail.ynu.edu.cn
 * Date:     2/6/2021
 * Description:
 *     孤儿进程组示例
 */
#include "apue.h"
#include <sys/errno.h>

static void pr_ids(char *name);
static void sig_hup(int signo);

int main(int argc, char *argv[]) {
  pr_ids("parent");
  pid_t pid;
  char c;
  if ((pid = fork()) < 0) {
    err_sys("fork error");
  } else if (pid > 0) {
    sleep(5);// sleep to let child stop itself
  } else {
    pr_ids("child");
    signal(SIGHUP, sig_hup);// establish signal handler
    kill(getpid(), SIGSTOP);       // stop ourself
    pr_ids("child");        // pritns only if we're continued
    if (read(STDIN_FILENO, &c, 1) != 1) {
      printf("read error %d on controlling TTY\n", errno);
    }
  }
  return 0;
}
void pr_ids(char *name) {
  printf("%s: pid = %ld, ppid = %ld, pgrp = %ld, tpgrp = %ld\n", name,
         (long) getpid(), (long) getppid(), (long) getpgrp(), (long) tcgetpgrp(STDIN_FILENO));
  fflush(stdout);
}
void sig_hup(int signo) {
  printf("SIGHUP received, pid = %ld\n", (long) getpid());
}